﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Antioch.Base.PlayerStates
{
    internal class LookAwayFromLedge : IState
    {
        public void Enter(StateMachine Machine)
        {
            Machine.DrawComponent.Play("LookAwayFromLedge", true);
            Machine.PhysicsComponent.PhysicsBody.GetFixtureList().SetFriction(0.0f);
        }

        public void Leave(StateMachine Machine)
        {
        }

        private void DetachLedgeHangJoint(StateMachine Machine)
        {
            Machine.PhysicsModule.PhysicsSimulator.DestroyJoint(Machine.Memory.LedgeHangJoint);
            Machine.Memory.LedgeHangJoint = null;
        }

        public void Update(StateMachine Machine)
        {
            if (Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Left && Machine.Input.NavigationStick.X <= 0)
                Machine.Transition(typeof(HangFromLedge));
            else if (Machine.PlayerEntity.Facing == Jemgine.Data.Facings.Right && Machine.Input.NavigationStick.X >= 0)
                Machine.Transition(typeof(HangFromLedge));
            else if (!Machine.Memory.LedgeHangPoint.CanHang(Machine.PlayerEntity))
            {
                DetachLedgeHangJoint(Machine);
                Machine.Transition(typeof(Fall));
            }
            else if (Machine.Input.JumpPressed)
            {
                Vector2 Right = Jemgine.Math.Vector.Normalize(Jemgine.Math.Vector.Perpendicular(-Machine.PhysicsComponent.Gravity));

                DetachLedgeHangJoint(Machine);
                switch (Machine.PlayerEntity.Facing)
                {
                    case Jemgine.Data.Facings.Left:
                        Machine.PhysicsComponent.PhysicsBody.ApplyLinearImpulse(Right * Machine.Settings.JumpForce,
                            Machine.PhysicsComponent.PhysicsBody.Position);
                        Machine.PlayerEntity.Facing = Jemgine.Data.Facings.Right;
                        break;
                    case Jemgine.Data.Facings.Right:
                        Machine.PhysicsComponent.PhysicsBody.ApplyLinearImpulse(-Right * Machine.Settings.JumpForce,
                           Machine.PhysicsComponent.PhysicsBody.Position);
                        Machine.PlayerEntity.Facing = Jemgine.Data.Facings.Left;
                        break;
                }
                Machine.Transition(typeof(Jump));
            }
        }
    }
}
